package thread;

/**
 * @User: vito_bo
 * @Date: 2024-07-30
 * @Description: 死锁出现情况
 *
 *  两个线程两把锁，t1和t2各自先针对锁A和锁B加锁，再尝试获取对方的锁；
 *
 *
 *
 */
public class ThreadDemo14 {


    public static void main(String[] args) {
        // 解决死锁:  假设 t1 是 1 号, cu 是 2 号, 约定先拿小的, 后拿大的.
        Object jiangyou = new Object();
        Object cu = new Object();

        Thread bobo = new Thread(() -> {
            synchronized (jiangyou) {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (cu) {
                    System.out.println("波波把酱油和醋都拿到了");
                }
            }
        });
        Thread yuanyuan = new Thread(() -> {
            synchronized (jiangyou) {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (cu) {
                    System.out.println("媛媛把酱油和醋都拿到了");
                }
            }
        });
        bobo.start();
        yuanyuan.start();
    }


    public static void main1(String[] args) {
        // 假设 jiangyou 是 1 号, cu 是 2 号, 约定先拿小的, 后拿大的.
        Object jiangyou = new Object();
        Object cu = new Object();

        Thread bobo = new Thread(() -> {
            synchronized (jiangyou) {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (cu) {
                    System.out.println("波波把酱油和醋都拿到了");
                }
            }
        });
        Thread yuanyuan = new Thread(() -> {
            synchronized (cu) {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (jiangyou) {
                    System.out.println("媛媛把酱油和醋都拿到了");
                }
            }
        });
        bobo.start();
        yuanyuan.start();
    }
}
